package com.boy.rpc.framework.console.utils;

import com.boy.rpc.framework.console.Constant;
import com.boy.rpc.framework.console.utils.redis.MyStringRedisTemplate;
import com.boy.rpc.framework.console.utils.ztree.RedisZtreeUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by wesley on 2017-03-20.
 */
public class InitRedisConnection {
    private static final Logger logger = LoggerFactory.getLogger(InitRedisConnection.class);

    public static void createRedisConnection(String name, String host, int port, String password, String keys) {
        logger.debug("InitRedisConnection: createRedisConnection start...");
        JedisConnectionFactory connectionFactory = new JedisConnectionFactory();
        connectionFactory.setHostName(host);
        connectionFactory.setPort(port);
        if(!StringUtils.isEmpty(password))
            connectionFactory.setPassword(password);
        connectionFactory.afterPropertiesSet();

        //保存RedisTemplate
        RedisTemplate redisTemplate = new MyStringRedisTemplate();
        redisTemplate.setConnectionFactory(connectionFactory);
        redisTemplate.afterPropertiesSet();
        Constant.redisTemplatesMap.put(name, redisTemplate);

        //把服务写入内存缓存中
        Map<String, Object> redisServerMap = new HashMap<String, Object>();
        redisServerMap.put("name", name);
        redisServerMap.put("host", host);
        redisServerMap.put("port", port);
        redisServerMap.put("password", password);
        Constant.redisServerCache.add(redisServerMap);

        //初始化redis-keys缓存
        InitKeysCacheUtil.initRedisKeysCache(redisTemplate, name, keys);

        RedisZtreeUtil.initRedisNavigateZtree(name);

        logger.debug("redisTemplatesMap--->>"+Constant.redisTemplatesMap+"redisServerCache--->"+Constant.redisServerCache);

    }
}
